class ListNode {
  val: number
  next: ListNode | null
  constructor(val?: number, next?: ListNode | null) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
  }
}

function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
  let nodeA = headA
  let nodeB = headB
  if (!headB) return null
  while (nodeA) {
    if (!nodeB) {
      // B遍历完 A取下一个继续比较
      nodeA = nodeA.next
      if (!nodeA) {
        return null
      }
      nodeB = headB
    }
    if (nodeA === nodeB) {
      return nodeA
    } else {
      nodeB = (nodeB as ListNode).next
    }
  }
  return null
};

/**
 * 双指针的思路太妙了
 */
function getIntersectionNode2(headA: ListNode | null, headB: ListNode | null): ListNode | null {
  let nodeA = headA
  let nodeB = headB
  if (!headB || !headA) return null
  while (nodeA !== nodeB) {
    nodeB = !nodeB ? headA : nodeB.next
    nodeA = !nodeA ? headB : nodeA.next
  }
  return nodeA
};